#include <errno.h>

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <strings.h>
#include <fcntl.h>

#include <sys/stat.h>
#include <sys/types.h>


#define BUF_SIZE 1024

void random_word( char buf[], size_t buf_size)
{
	srandom( getpid() );
	
	int i;
	for ( i = 0; i < buf_size; i++)
	{
		char tmp = 'a' + (char)( ( (float)random() / RAND_MAX ) * 26);
		buf[i] = tmp;
	}
	buf[ buf_size] = 0;
}


int main( int argc, char** argv)
{
    if ( argc != 2)
    {
        printf("Wrong arguments\n");
        exit(1);
    }
    
    int fd_in = open( (char*)argv[1],O_RDONLY);
    if ( fd_in == -1)
	{
		printf("Can't open input file\t%s\n",(char*)argv[1]);
		perror("fd_in");
		exit(0);
	}
////////////////////////	
	char   fifo_name[9];
	char   tmp[256];
	
	struct stat tmp_buf;
	int T = 1;
	do
	{
		random_word( tmp, 5);
	
		strcpy( fifo_name, "zzz");
		strcat( fifo_name, tmp  );
	}
	while( ( mkfifo( fifo_name,0644) == -1) && ( errno == EEXIST));
////////////////////////
	mkfifo( "MAIN_FIFO",  0644);
	int fd_main_fifo = open( "MAIN_FIFO", O_WRONLY);

	while ( write( fd_main_fifo, fifo_name, 8) != 8);
	
	fifo_name[8] = '\0';
	
	int fd_fifo = open( fifo_name, O_WRONLY);
//////////////////////////
	char   buf[ BUF_SIZE];
	
	int read_count;
	int write_count;
	do
	{
		read_count = read( fd_in, buf, BUF_SIZE);
		write_count = 0;
		do
		{
			int tmp = write( fd_fifo, buf + write_count, read_count - write_count);
			if ( tmp == -1)
			{
				if ( errno == EINTR)
				{
					continue;
				}else
				{
					perror("Out write error");
					exit(0); 
				}
			}
			write_count +=tmp;
		}
		while ( write_count != read_count);
		
	}while( read_count > 0);
//////////////////////////
}
